package com.example.news_reader;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

public class MainActivity extends Activity {

	private ArrayList<String> mGroupList = null;    
	private ArrayList<ArrayList<DataList>> mChildList = null;    
	private ExpandableListView mListView=null;
	private C_Adapter adapter = null;
	private final int DID = 0;
	private final int WHAT = 0;
	private NewsList nList = null;
	EditText text;String aa;

	Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what){
				case WHAT:
					mListView.setAdapter(adapter);

					// 차일드 클릭 했을 경우 이벤트        
					mListView.setOnChildClickListener(new OnChildClickListener() {             
						@Override            
						public boolean onChildClick(ExpandableListView parent, View v,                     
								int groupPosition, int childPosition, long id) {   
							String link = mChildList.get(groupPosition).get(childPosition).getLink();
							if(link!=null){
							Intent i = new Intent(MainActivity.this, WebLink.class);
							i.putExtra("link", link);
							startActivity(i);
							}
							return false;             
						}         
					});                   

					int cnt = mListView.getCount();
					for(int i=0; i<cnt; i++){
						mListView.expandGroup(i);
					}

					removeDialog(DID);
					break;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "언론사 선택");
		menu.add(Menu.NONE, Menu.FIRST+2, Menu.NONE, "카테고리 선택");
		menu.add(Menu.NONE, Menu.FIRST+3, Menu.NONE, "키워드 검색");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		boolean a = false;
		Toast t;

		switch(item.getItemId()){
			case Menu.FIRST+1:
				showDialog(DID+1);
			a=true;
			break;
			case Menu.FIRST+2:
				showDialog(DID+2);
			a=true;
			break;
			case Menu.FIRST+3:
				showDialog(DID+3);
			a=true;
			break;
		}

		return (a || super.onOptionsItemSelected(item));
	}

	@Override   
	public void onCreate(Bundle savedInstanceState) {       
		super.onCreate(savedInstanceState);       
		setContentView(R.layout.main);         
		mListView = (ExpandableListView)findViewById(R.id.news_lv);
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		mListView.setIndicatorBounds(width-50, width);
		//		mListView.setGroupIndicator(null);

		nList = new NewsList(this);

		mGroupList = new ArrayList<String>();         

		runData();

	}       


	protected void runData(){
		showDialog(DID);
		Thread thread = new Thread(){
			public void run(){
				mGroupList = nList.getCategoryName();
				mChildList = new ArrayList<ArrayList<DataList>>();
				
				for(int i=0;i<mGroupList.size();i++){
					DataParsing parser = new DataParsing(nList.getNews_url(i));
					mChildList.add(parser.getAllData());
				}
				adapter = new C_Adapter(MainActivity.this, mGroupList, mChildList);
				Message msg = handler.obtainMessage(WHAT);
				handler.sendMessage(msg);

			}
		};
		thread.start();
	}

	protected void runData(String a){
		aa = a;
		showDialog(DID);
		Thread thread = new Thread(){
			public void run(){
				mGroupList.clear();
				mGroupList.add(aa);
				mChildList = new ArrayList<ArrayList<DataList>>();
				String query = null;

				try {
					query = URLEncoder.encode(aa, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String url = "http://news.google.co.kr/news?q="+
						query+
						"&hl=ko&newwindow=1&prmd=imvnsul&bav=on.2,or.r_gc.r_pw.r_qf.&biw=1600&bih=809&um=1&ie=UTF-8&output=rss";

				DataParsing parser = new DataParsing(url);
				mChildList.add(parser.getData());
				adapter = new C_Adapter(MainActivity.this, mGroupList, mChildList);
				Message msg = handler.obtainMessage(WHAT);
				handler.sendMessage(msg);
				
			}
		};
		thread.start();
	}

	protected Dialog onCreateDialog(int id){
		ProgressDialog d = new ProgressDialog(this);
		AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
		AlertDialog alert;
		switch(id){
			case DID:
				d.setMessage("Loding...");
				d.setIndeterminate(true);
				d.setCancelable(true);
				return d;
			case DID+1:
				b.setTitle("언론사를 선택하세요.");
			b.setSingleChoiceItems(R.array.news, 0, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					nList.setCntN(which);
				}
			});
			b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					runData();  
				}});
			alert = b.create();
			return alert;
			case DID+2:

				nList.setCntCAll();
				b.setTitle("카테고리를 선택하세요.");
			b.setMultiChoiceItems(R.array.category, null, new DialogInterface.OnMultiChoiceClickListener() {

				@Override 
				public void onClick(DialogInterface dialog, int which, boolean isChecked) {
					nList.setCntC(which, isChecked);
					Log.i("which",which+"");
					Log.i("checked",isChecked+"");
				}
			});
			b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					runData();  
				}});
			alert = b.create();
			return alert;
			case DID+3:
				b.setTitle("키워드를 입력해 주세요.");
			text = new EditText(MainActivity.this);
			b.setView(text);
			
			b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					String a = text.getText().toString();
					nList.setKey(a);
					runData(a);					
				}
			});
			b.setNegativeButton("취소", null);
			alert = b.create();
			return alert;

		}
		return d;
	}
}
